﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using ConfExpert.Forms.Kalite;
using ConfExpert.Utility;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraReports.UI;
using DevExpress.XtraVerticalGrid.Events;
using DevExpress.XtraVerticalGrid.Rows;
using DevTeam;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Planlama
{
    public partial class UretimTakip : XForm
    {
        public UretimTakip()
        {
            InitializeComponent();
        }

        int DagilimId;
        Color[] colors;
        BindingSource bs, bsL, bsLh, bsLm, bsLg, bsD, bsF, bsExcel, bsLa, bsLi, bsLt, bsGM, bsGMPl;

        private void Planlama_Load(object sender, EventArgs e)
        {
            tpGarniMetrajPl.PageVisible = ytk(158); //pazarlama | planlama

            TAM.PlanlamaTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaTableAdapter();
            TAM.PlanlamaGarniMetrajTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaGarniMetrajTableAdapter();
            TAM.PlanlamaGarniMetrajPlTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaGarniMetrajPlTableAdapter();
            TAM.PlanlamaLinesTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaLinesTableAdapter();
            TAM.PlanlamaLinesHatalarTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaLinesHatalarTableAdapter();
            TAM.PlanlamaLinesGarniTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaLinesGarniTableAdapter();
            TAM.PlanlamaLinesModelhaneTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaLinesModelhaneTableAdapter();
            TAM.PlanlamaDagilimTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaDagilimTableAdapter();
            TAM.PlanlamaFaturaTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaFaturaTableAdapter();
            TAM.PlanlamaLinesInvoiceTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaLinesInvoiceTableAdapter();
            TAM.PlanlamaLinesAksesuarTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaLinesAksesuarTableAdapter();
            TAM.PlanlamaLinesTelaTableAdapter = new Datasets.MyDataTableAdapters.PlanlamaLinesTelaTableAdapter();

            ds.PlanlamaLinesHatalar.Columns.Add("Kalite2", typeof(int), "Iif(Etkisi=1, Adet, Null)");
            ds.PlanlamaLinesHatalar.Columns.Add("Kalite3", typeof(int), "Iif(Etkisi=2, Adet, Null)");

            ds.PlanlamaDagilim.Columns.Add("S", typeof(int));
            ds.PlanlamaDagilim.Columns.Add("K", typeof(int));
            ds.PlanlamaDagilim.Columns.Add("PMetraj", typeof(decimal), "Iif(ISNULL(Total,0)>0, PBoy/Total, Null)");

            ds.PlanlamaLines.Columns.Add("YuklemeTarihi", typeof(DateTime));
            ds.PlanlamaLines.Columns.Add("PastalBM", typeof(decimal));

            ds.Planlama.Columns.Add("KaliteGuvence", typeof(int));

            bs = new BindingSource(ds, "Planlama");
            bsGM = new BindingSource(bs, "FK_PlanlamaGarniMetraj_Planlama_PlanlamaId");
            bsGMPl = new BindingSource(bs, "FK_PlanlamaGarniMetrajPl_Planlama_PlanlamaId");
            bsL = new BindingSource(bs, "FK_PlanlamaLines_Planlama_PlanlamaId");
            bsLi = new BindingSource(bsL, "FK_PlanlamaLinesInvoice_PlanlamaLines_PlanlamaLinesId");
            bsLh = new BindingSource(bsL, "FK_PlanlamaLinesHatalar_PlanlamaLines_PlanlamaLinesId");
            bsLm = new BindingSource(bsL, "FK_PlanlamaLinesModelhane_PlanlamaLines_PlanlamaLinesId");

            bsLg = new BindingSource(bsL, "FK_PlanlamaLinesGarni_PlanlamaLines_PlanlamaLinesId");
            bsD = new BindingSource(bsL, "FK_PlanlamaDagilim_PlanlamaLines_PlanlamaLinesId");
            bsF = new BindingSource(bs, "FK_PlanlamaFatura_Planlama_PlanlamaId");
            bsLa = new BindingSource(bsL, "FK_PlanlamaLinesAksesuar_PlanlamaLines_PlanlamaLinesId");
            bsLt = new BindingSource(bsL, "FK_PL_PLT_PlanlamaLinesId");
            AddBsToList(bs, bsL, bsLh, bsLg, bsLm, bsD, bsF, bsLa, bsLi, bsLt, bsGM, bsGMPl);

            bsExcel = new BindingSource(ds, "xPlanlamaXls");

            InitGridView(gv, bs);
            //gv.Columns["DosyaNo"].ColumnEdit = new RepositoryItemTextEdit();

            if (ytk(105))
                ((RepositoryItemTextEdit)gv.Columns["DosyaNo"].ColumnEdit).MaxLength = 8;
            else
            {
                ((RepositoryItemTextEdit)gv.Columns["DosyaNo"].ColumnEdit).MaxLength = 1;
                ((RepositoryItemTextEdit)gv.Columns["DosyaNo"].ColumnEdit).Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                ((RepositoryItemTextEdit)gv.Columns["DosyaNo"].ColumnEdit).Mask.EditMask = "[KFND]";
            }

            gv.SetCaptions("YuklemeHaftasi:Haftası", "YuklemeAyi:Ayı");

            InitGridView(gvGarni, bsGM);
            InitGridView(gvGarniPl, bsGMPl);
            InitGridView(gvLines, bsL);
            InitGridView(gvHatalar, bsLh);
            InitGridView(gvModelhane, bsLm);
            InitGridView(gvGarniArt, bsLg);
            InitGridView(gvDagilim, bsD);
            InitGridView(gvMyTreeLines, bsLa);
            InitGridView(gvTela, bsLt);

            gvGarni.EnableRowDelete();

            if (!ytk(103))   //Serap ve Meltem hanım
            {
                gvGarni.MakeReadOnly();
                gvModelhane.MakeReadOnly();
            }

            if (!ytk(212)) //omer.bozdag ve ozcan.cicek
            {
                gvHatalar.MakeReadOnly();
            }

            if (!ytk(209)) //planlamacı + mt
            {
                gvMyTreeLines.MakeReadOnly();
            }

            gvHatalar.EnableRowDelete();
            gvModelhane.EnableRowDelete();
            gvLines.EnableRowDelete();

            gvMyTreeLines.Columns["Qty"].DisplayFormat.FormatString = "#,##0.#";
            gvLines.OptionsView.EnableAppearanceEvenRow = false;
            gvDagilim.Columns["PMetraj"].VisibleIndex = gvDagilim.Columns["PKat"].VisibleIndex + 1;
            gvDagilim.FormatAsNumber(2, "PMetraj");
            gvDagilim.RowCellStyle += new RowCellStyleEventHandler(gvDagilim_RowCellStyle);

            int cnt = 0;
            gv.Images = bandImages;
            string[] parts = "DOSYA BİLGİLERİ;KESİLEN ADET DAĞILIMI;INVOICE;FATURA;DİĞER".Split(';');   //ÜRETİMDEN KALAN KUMAŞ TAKİBİ
            string[] starts = "PlanlamaId;Yuklenen;YuklemeTarihi;Adet;NOTLAR;".Split(';');
            for (int i = 0; i < parts.Length; i++)
            {
                GridBand gb = new DevExpress.XtraGrid.Views.BandedGrid.GridBand();
                gb.Caption = "<b>" + parts[i] + "</b>";
                gb.ImageIndex = i;
                gb.Name = "gb" + gb.ImageIndex.ToString();
                //TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                gb.OptionsBand.AllowHotTrack = true;
                gv.Bands.Add(gb);

                for (int i2 = cnt; i2 < gv.Columns.Count; i2++)
                {
                    if (gv.Columns[cnt].FieldName == starts[i + 1] && cnt > 0)
                        break;

                    if (cnt == 3)
                        gv.Bands[i].Columns.Add(gv.Columns["PrdTreeId"]);

                    if (gv.Columns[cnt].FieldName != "PrdTreeId")
                        gv.Bands[i].Columns.Add(gv.Columns[cnt]);

                    cnt++;
                }
            }

            //RepositoryItemGridLookUpEdit ri = new RepositoryItemGridLookUpEdit();
            //ri.DataSource = new DataView(ExecDatatable("GetPrdTree"));
            //ri.DisplayMember = "Name";
            //ri.ValueMember = "PrdTreeId";
            //ri.NullText = string.Empty;

            gv.Columns["PrdTreeId"].ColumnEdit = RI(Rp.PrdTree);

            gvLines.MakeColumnsReadOnly("KaufIdx");

            gv.OptionsView.AllowHtmlDrawHeaders = true;
            gv.SetViewCaption("Dosya Bilgileri");
            gvLines.SetViewCaption("Artikeller");
            gvHatalar.SetViewCaption("Üretim Hataları");
            gvModelhane.SetViewCaption("Modelhane Bilgileri");
            gvMyTreeLines.SetViewCaption("Aksesuar");
            gvGarniArt.SetViewCaption("Garniler");
            gvGarni.SetViewCaption("Garni Metraj ve Pozisyonları");
            gvGarniPl.SetViewCaption("Garni Tahmini Metrajları");
            gvDagilim.SetViewCaption("Beden Dağılımı + Birim Metraj");
            //gvMyTreeLines.SetViewCaption("Ürün Ağacı");
            gvTela.SetViewCaption("Kullanılan Tela");

            gv.Columns["PrdTreeId"].Caption = "Ürün Ağacı";
            gv.Columns["PrdTreeId"].Visible = false;

            Exp1();

            gvLines.Columns["PastalBM"].VisibleIndex = gvLines.Columns["TahminiBM"].VisibleIndex + 1;

            gv.AddSummary("SiparisAdedi", "KesimAdedi", "Yuklenen", "KalanKalite1", "EksikAdet", "Numune", "Iptal", "Kalite2", "Kalite3", "Fark", "Adet", "FaturaAdedi", "FaturaFark");
            gvLines.AddSummary("SiparisAdedi", "Kesilen", "Yuklenen", "KalanKalite1", "Iptal", "Kalite2", "Kalite3", "SarfedilenMt");
            gvHatalar.AddSummary("Adet");
            gvHatalar.MakeColumnVisible("InsertedOn");

            GridManager gm = GridManager.GetManager(gv);
            gm.GridMenu.AddMenu("Faturalar", Faturalar);
            gm.GridMenu.AddMenu("Excele Aktar", ExceleAktar);
            gm.GridMenu.AddMenu("Excele Aktar (+Fark)", ExceleAktarF);
            if (ytk(102))
            {
                gv.Columns["PrdTreeId"].Visible = true;
                gm.GridMenu.AddMenu("Ürün Ağacı Belirle", SpecifyPrdTree);
                gm.GridMenu.AddMenu("Aksesuar İhtiyacını Çıkar", CreateAksesuarTalep);
            }
            //gm.GridMenu.AddMenu("Kumaş İhtiyacını Çıkar", CreateFabricRequest);
            //gm.GridMenu.AddMenu("Tela İhtiyacını Çıkar", CreateTelaRequest);
            gm.GridMenu.AddMenu("Dosya Kapama Raporu Çıkar", DosyaKapama);
            gm.GridMenu.AddMenu("Kesilen Adet Etiketi Çıkar", PrintSticker);
            //gm.GridMenu.AddMenu("Excelden Al", ExceldenOku);

            GridManager gm2 = GridManager.GetManager(gvLines);
            if (ytk(101))    //Orhan+Deniz
                gm2.GridMenu.AddMenu("Dosya ayır", DosyaAyir);
            gm2.GridMenu.AddMenu("Invoice", Invoice);
            gm2.GridMenu.AddMenu("Excele Aktar", ExceleAktar2);
            gm2.GridMenu.AddMenu("Excele Aktar (+Fark)", ExceleAktar2F);
            gm2.GridMenu.AddMenu("Artikel Bul", FindSimilarArtikel);
            if (ytk(99))    //Serap ve Meltem (modelhane) -- Bu kişilerin yaptıklarını rol olarak tanımlamak gerekli!
                gm2.GridMenu.AddMenu("Metraj Satırları Oluştur ve Kaydet (tüm artikeller için)", OrtalamaMetrajHesapla);

            DagilimId = 1;
            //gleDagilim.Properties.Assign(RI(Rp.Dagilim));
            //gleDagilim.EditValueChanged += new EventHandler(gleDagilim_EditValueChanged);
            //gleDagilim.EditValue = 1;
            //GleExtend(gleDagilim);

            gvMyTreeLines.OptionsView.NewItemRowPosition =
            gv.OptionsView.NewItemRowPosition =
            gvLines.OptionsView.NewItemRowPosition =
            gvHatalar.OptionsView.NewItemRowPosition =
            gvModelhane.OptionsView.NewItemRowPosition =
            gvGarniArt.OptionsView.NewItemRowPosition =
            gvGarni.OptionsView.NewItemRowPosition =
            gvGarniPl.OptionsView.NewItemRowPosition =
            gvTela.OptionsView.NewItemRowPosition =
            gvDagilim.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;

            //gvGarni.FormatAsNumber(1, "Cm");
            gvGarniPl.FormatAsNumber(1, "Cm");

            gvLines.FormatAsNumber(0, "SiparisAdedi", "Kesilen", "Yuklenen", "KalanKalite1", "Iptal", "Kalite2", "Kalite3", "Yuklenen2Kalite");
            gvLines.FormatAsNumber(1, "SarfedilenMt");
            gvLines.FormatAsNumber(2, "KumasEni");
            gvLines.FormatAsNumber(3, "TahminiBM", "PastalBM");


            gv.FormatAsNumber(0, "SiparisAdedi", "KesimAdedi", "Yuklenen", "KalanKalite1", "EksikAdet", "Numune", "Iptal", "Kalite2", "Kalite3", "Fark", "Adet", "FaturaAdedi", "FaturaFark");

            gvModelhane.FormatAsNumber(3, "OrtBirimMetraj");

            gvDagilim.FormatAsNumber(0,
                "A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10",
                "A11", "A12", "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20",
                "A21", "A22", "A23", "A24", "A25", "A26", "A27", "A28");

            gvDagilim.Columns["SipKes"].ColumnEdit = GetCustomRI("Tür", true, "Sipariş Adedi", "Kesilen Adet", "Pastal");
            foreach (string str in "PlanlamaDagilimId;PlanlamaLinesId;Total;S;K;UserId".Split(';'))
                gvDagilim.Columns[str].Visible = false;

            gvHatalar.Columns["Etkisi"].ColumnEdit = GetCustomRI("Etkisi", true, "2. Kalite", "3. Kalite");
            foreach (string str in "PlanlamaLinesHatalarId;PlanlamaLinesId;Kalite2;Kalite3".Split(';'))
                gvHatalar.Columns[str].Visible = false;

            foreach (string str in "PlanlamaLinesGarniId;PlanlamaLinesId;UserId".Split(';'))
                gvGarniArt.Columns[str].Visible = false;

            foreach (string str in "PlanlamaGarniMetrajId;PlanlamaId;UserId".Split(';'))
                gvGarni.Columns[str].Visible = false;

            foreach (string str in "PlanlamaGarniMetrajPlId;PlanlamaId;UserId".Split(';'))
                gvGarniPl.Columns[str].Visible = false;

            foreach (string str in "PlanlamaLinesAksesuarId;PlanlamaLinesId".Split(';'))
                gvMyTreeLines.Columns[str].Visible = false;

            foreach (string str in "PlanlamaLinesModelhaneId;PlanlamaLinesId;UserId".Split(';'))
                gvModelhane.Columns[str].Visible = false;

            gvModelhane.Columns["ModifiedOn"].Visible = true;

            //TODO: tekrar aç!
            foreach (string str in "PlanlamaId;PlanlamaLinesId".Split(';'))
                gvLines.Columns[str].Visible = false;

            foreach (string str in "PlanlamaLinesTelaId;PlanlamaLinesId".Split(';'))
                gvTela.Columns[str].Visible = false;

            RepositoryItem ri = RI(Rp.Tela);
            gvTela.Columns["Yaka"].ColumnEdit = ri;
            gvTela.Columns["Kusak"].ColumnEdit = ri;
            gvTela.Columns["Poligot"].ColumnEdit = ri;
            gvTela.Columns["Manset"].ColumnEdit = ri;
            gvTela.Columns["EkstraTela"].ColumnEdit = ri;

            ds.Planlama.TableNewRow += new DataTableNewRowEventHandler(Planlama_TableNewRow);
            ds.PlanlamaLines.TableNewRow += new DataTableNewRowEventHandler(PlanlamaLines_TableNewRow);

            (gv.Columns["DagilimId"].ColumnEdit as RepositoryItemGridLookUpEdit).EditValueChanged += new EventHandler(Planlama_EditValueChanged);

            colors = new Color[]{
                Color.FromArgb(238, 243, 213),
                Color.FromArgb(234, 247, 249),
                Color.FromArgb(219, 238, 243),
                Color.FromArgb(179, 219, 229),
                Color.FromArgb(238, 243, 213)
                };

            PrepareImageComboBoxEdit(gv, "FaturaDurumu");

            gv.OptionsView.EnableAppearanceEvenRow = false;
            gv.RowCellStyle += new RowCellStyleEventHandler(gvListe_RowCellStyle);
            splitContainerControl2.AutoSize();

            gv.Columns["YuklemeTarihi"].ColumnEdit = new RepositoryItemDateEdit();
            foreach (string str in "YuklemeHaftasi;YuklemeAyi".Split(';'))
            {
                gv.Columns[str].ColumnEdit = new RepositoryItemDateEdit();
                gv.Columns[str].OptionsColumn.AllowEdit = false;
            }

            //ÖNEMLİ: Set the ShowWeekNumbers property to true to display week numbers (relative to the first week of the current year) in the dropdown window. Week numbers are displayed at the left of the calendar.
            (gv.Columns["YuklemeTarihi"].ColumnEdit as RepositoryItemDateEdit).ShowWeekNumbers = true;
            (gv.Columns["YuklemeHaftasi"].ColumnEdit as RepositoryItemDateEdit).DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            (gv.Columns["YuklemeHaftasi"].ColumnEdit as RepositoryItemDateEdit).DisplayFormat.Format = new FormatHafta();
            (gv.Columns["YuklemeAyi"].ColumnEdit as RepositoryItemDateEdit).DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            (gv.Columns["YuklemeAyi"].ColumnEdit as RepositoryItemDateEdit).DisplayFormat.FormatString = "MMMM";
            //http://documentation.devexpress.com/#WindowsForms/CustomDocument1497

            gv.Columns["KalanKalite1"].Caption = "Kalan I. Kalite";
            gv.Columns["Kalite2"].Caption = "II. Kalite";
            gv.Columns["Kalite3"].Caption = "III. Kalite";

            gvDagilim.Columns["SipKes"].Caption = "Tür";

            //kapamaları sadece 92,87,57 yapabilsin. 
            btnKaydet.Enabled = gvLines.OptionsBehavior.Editable = gvDagilim.OptionsBehavior.Editable = ytk(95);

            if (gv.RowCount > 0)
                txtInfo.Caption = strParse(bs, "DosyaNo");



            //ÖNEMLİ: http://www.devexpress.com/Support/Center/p/K18343.aspx

            gv.MakeCompulsory("DosyaNo");
            gvLines.RowStyle += new RowStyleEventHandler(gvLines_RowStyle);
            //MakeCompulsory(gvDagilim, "SipKes");
            foreach (GridColumn col in gv.Columns)
                if (col.ColumnType == typeof(DateTime))
                {
                    //col.ColumnEdit = new RepositoryItemDateEdit();
                    //((RepositoryItemDateEdit)col.ColumnEdit).VistaDisplayMode = DefaultBoolean.True;
                    //col.ColumnEdit = new RepositoryItemDateEdit();
                    //(col.ColumnEdit as RepositoryItemTextEdit).Mask.UseMaskAsDisplayFormat = true;
                    //(col.ColumnEdit as RepositoryItemTextEdit).Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTime;
                    //(col.ColumnEdit as RepositoryItemTextEdit).Mask.EditMask = @"dd.MM.yyyy";
                    col.OptionsFilter.FilterPopupMode = FilterPopupMode.DateSmart;
                }
                else
                    col.OptionsFilter.FilterPopupMode = FilterPopupMode.CheckedList;



            //radioGroup1.SelectedIndex = -1;
            //radioGroup1.SelectedIndexChanged += new EventHandler(radioGroup1_SelectedIndexChanged);
            //radioGroup1.SelectedIndex = 0;

            //dateEdit1.DateTimeChanged += new EventHandler(dateEdit1_DateTimeChanged);
            //dateEdit1.EditValue = new DateTime(2011, 7, 1);

            btnKaydet.ItemClick += btnKaydet_ItemClick;
            btnGetir.Click += new EventHandler(btnGetir_Click);
            btnTemizle.Click += new EventHandler(btnTemizle_Click);

            CreateVerticalGrid();

            //btnGetir.PerformClick();

            ds.PlanlamaLinesHatalar.TableNewRow += new DataTableNewRowEventHandler(PlanlamaLinesHatalar_TableNewRow);
            bs.CurrentChanged += new EventHandler(bs_CurrentChanged);
            txtInfo.Caption = strParse(bs, "DosyaNo");
            DagilimChanged(intParse(bs, "DagilimId"));

            gv.Columns["NumuneUretim"].ColumnEdit = GetCustomRI("Numune Üretim", false, "NUMUNE", "ÜRETİM", "KOLEKSİYON");
            gvModelhane.Columns["YikamaBilgisi"].ColumnEdit = GetCustomRI("Yıkama Bilgisi", false, "YIKAMALI", "YIKAMASIZ");
            this.FormClosing += new FormClosingEventHandler(UretimTakip_FormClosing);

            gv.DoubleClick += new EventHandler(gv_DoubleClick);
            //Notify("Formun hızlı açılması için kayıtlar yüklenmedi. Filtre girdikten sonra GETİR butonuna tıklayınız.");

            gv.ShowingEditor += gv_ShowingEditor;

            btnSorunlu.ItemClick += btnSorunlu_ItemClick;
            btnSorunlu.Visibility = ytk(17) ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;
            btnEksikler.ItemClick += btnEksikler_ItemClick;
            btnEksikler.Visibility = ytk(92) ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;  //TODO: sorunlu planlamalinesId'lerin PKat'larını sıfırladıktan sonra bunu çalıştır!

            RepositoryItemHyperLinkEdit riPOId = new RepositoryItemHyperLinkEdit();
            riPOId.SingleClick = true;
            gv.Columns["KaliteGuvence"].ColumnEdit = riPOId;
            AddTooltip(gv, "KaliteGuvence", "Buradaki sayı Kalite Güvence bölümünün bu dosya için tarattığı evrak sayısını göstermektedir. Bu sayıya tıklayarak taranmış olan belgeleri görüntüleyebilirsiniz.");

            gv.RowCellClick += gv_RowCellClick;
            gvDagilim.ShowingEditor += gvDagilim_ShowingEditor;
            GridManager.GetManager(gvDagilim).Pasting += UretimTakip_Pasting;
            GridManager.GetManager(gvDagilim).RowDeleteDisabled = false;


            RepositoryItemDateEdit ride = new RepositoryItemDateEdit();

            ride.CalendarTimeEditing = DevExpress.Utils.DefaultBoolean.True;
            ride.EditMask = "g";
            ride.Mask.UseMaskAsDisplayFormat = true;
            ride.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTimeAdvancingCaret;

            gv.Columns["DosyaTeslimTarihi"].ColumnEdit = ride;
        }

        void UretimTakip_Pasting(int rowHandle, GridColumn column, object val, System.ComponentModel.CancelEventArgs ce)
        {
            ce.Cancel = !AllowEdit1();
        }

        void gvDagilim_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = !AllowEdit1();
        }

        private bool AllowEdit1()
        {
            bool res = gvDagilim.GetFocusedDataRow()==null ||
                (
                gvDagilim.GetFocusedDataRow()["SipKes"].ToInt() == 1 &&
                ytk(218)/*MP*/ &&
                !ytk(222)/*Tülay*/ ||
                
                gvDagilim.GetFocusedDataRow()["SipKes"].ToInt() == 2 &&
                ytk(219)/*Özcan+Tülay+Emre.tomac*/ ||
                
                gvDagilim.GetFocusedDataRow()["SipKes"].ToInt() == 2 &&
                ytk(220)/*Fevzi*/ &&
                "KN".Contains(gv.GetFocusedDataRow()["DosyaNo"].ToStr().Substring(0, 1)) ||
            
                gvDagilim.GetFocusedDataRow()["SipKes"].ToInt() == 3 &&
                ytk(221)/*Modelhane*/ ||

                gvDagilim.GetFocusedDataRow()["PlanlamaDagilimId"].ToInt()<0
                );

            return res;
        }


        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ds.PlanlamaLinesHatalar.Select("Etkisi is null").Length > 0)
            {
                ShowErrorMessage("Etkisi alanı boş olamaz!");
                return;
            }

            gv.EndEditing();
            gvLines.EndEditing();
            try
            {
                Exp0();
                if (DosyaNolari())
                {
                    Save();
                    Notify("Saved.");
                    Session.DataManager.ExecuteNonQuery("UpdDu4DurumFromPlanlama");
                }
                Exp1();

                gv.UpdateTotalSummary();
                gvLines.UpdateTotalSummary();

            }
            catch (Exception Ex)
            {
                //if (Ex.Message.Contains("Violation of UNIQUE KEY constraint"))
                throw Ex;
            }
        }

        void btnEksikler_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ClearTables();
            GetDetails("Planlama;PlanlamaLines;PlanlamaLinesHatalar;PlanlamaLinesGarni;PlanlamaLinesModelhane;PlanlamaDagilim;PlanlamaFatura;PlanlamaLinesInvoice;PlanlamaLinesAksesuar;PlanlamaLinesTela;PlanlamaGarniMetraj;PlanlamaGarniMetrajPl",
                "GetPlanlamaEksikler");
            gv.BestFitColumns();
            gvLines.BestFitColumns();
            gvGarniArt.BestFitColumns();
            gvGarniPl.BestFitColumns();
            gvGarni.BestFitColumns();

            txtInfo.Caption = strParse(bs, "DosyaNo");
            DagilimChanged(intParse(bs, "DagilimId"));

            for (int i = 0; i < gv.DataRowCount; i++)
            {
                SetPKat();
                bs.MoveNext();
            }

            Exp0();
            Save();
            Exp1();
            Notify("Done.");
        }

        void btnSorunlu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ClearTables();
            GetDetails("Planlama;PlanlamaLines;PlanlamaLinesHatalar;PlanlamaLinesGarni;PlanlamaLinesModelhane;PlanlamaDagilim;PlanlamaFatura;PlanlamaLinesInvoice;PlanlamaLinesAksesuar;PlanlamaLinesTela;PlanlamaGarniMetraj;PlanlamaGarniMetrajPl",
                "GetPlanlamaSorunlu");
            gv.BestFitColumns();
            gvLines.BestFitColumns();
            gvGarniArt.BestFitColumns();
            gvGarniPl.BestFitColumns();
            gvGarni.BestFitColumns();

            txtInfo.Caption = strParse(bs, "DosyaNo");
            DagilimChanged(intParse(bs, "DagilimId"));

            Notify("Done.");
        }

        void gv_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "KaliteGuvence")
                if (gv.GetFocusedDataRow() != null)
                    if (gv.GetFocusedDataRow()["KaliteGuvence"].ToStr() != string.Empty)
                    {
                        string DosyaNo = gv.GetFocusedDataRow()["DosyaNo"].ToStr();
                        using (Detay detay = new Detay(DosyaNo))
                            detay.ShowDialog();
                    }
        }

        private void PrintSticker(object sender, EventArgs e)
        {
            int PlanlamaId = gv.GetRowCellValue(gv.FocusedRowHandle, "PlanlamaId").ToInt();
            Rapor.xrKesilenAdetSticker ka = new Rapor.xrKesilenAdetSticker(PlanlamaId);
            ka.ShowPreview();
        }

        void gv_DoubleClick(object sender, EventArgs e)
        {
            if (gv.FocusedRowHandle > -1)
            {
                gvLines.BestFitColumns();
                gvDagilim.BestFitColumns();

                xtraTabControl2.SelectedTabPage = tpDetay;
            }
        }

        void UretimTakip_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (btnKaydet.Enabled)
                if (ds.HasChanges())
                    if (XtraMessageBox.Show("Değişiklikleri kaydetmek ister misiniz?", "Critical", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                        btnKaydet.PerformClick();
        }

        void gvDagilim_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
                switch (e.Column.FieldName)
                {
                    case "PBoy":
                    case "PKat":
                    case "PMetraj":
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        break;
                    case "SipKes":
                        e.Appearance.BackColor = intParse(gvDagilim.GetRowCellValue(e.RowHandle, "SipKes")) < 3 ? Color.LightSkyBlue : Color.White;
                        break;
                }
        }

        void bs_CurrentChanged(object sender, EventArgs e)
        {
            txtInfo.Caption = strParse(bs, "DosyaNo");
            DagilimChanged(intParse(bs, "DagilimId"));

            //gvLines.Columns["Artikel"].VisibleIndex = intParse(bs, "PlanlamaId") > 0 && intParse(bs, "PlanlamaId") < 3188 ? gvLines.Columns["ProductId"].VisibleIndex + 1 : -1;
        }

        void PlanlamaLinesHatalar_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["Etkisi"] = 1;
        }

        void gvLines_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.RowHandle > -1)
                if (e.RowHandle == view.FocusedRowHandle)
                    e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;
        }

        void ExceldenOku(object sender, EventArgs e)
        {
            XtraMessageBox.Show("Çok yakında.");
        }

        void Faturalar(object sender, EventArgs e)
        {
            using (Fatura f = new Fatura(ref bsF))
            {
                f.ShowDialog();
            }
        }

        void OrtalamaMetrajHesapla(object sender, EventArgs e)
        {
            SetPKat();

            Exp0();
            Save();
            Exp1();
        }

        void Invoice(object sender, EventArgs e)
        {
            using (Invoice f = new Invoice(ref bsLi))
            {
                f.ShowDialog();
            }
        }

        //int[] selectedRows = gvLines.GetSelectedRows();
        //for (int i = 0; i < selectedRows.Length; i++)
        //    int rowHandle = selectedRows[i];

        int currentPlanlamaLinesId;
        private DataTable dtDagilim
        {
            get
            {
                DataRow[] drs = ds.PlanlamaDagilim.Select("PlanlamaLinesId=" + currentPlanlamaLinesId.ToString() + " AND SipKes=3");
                if (drs.Length > 0)
                    return drs.CopyToDataTable();
                else
                    return null;
            }
        }

        private int SiparisAdedi(string colName)
        {
            if (ds.PlanlamaDagilim.Select("PlanlamaLinesId=" + currentPlanlamaLinesId.ToString() + " AND SipKes=1").Length > 0)
                return ds.PlanlamaDagilim.Select("PlanlamaLinesId=" + currentPlanlamaLinesId.ToString() + " AND SipKes=1")[0][colName].ToInt();
            else
                return 0;
        }

        private void SetPKat()
        {
            bsD.EndEdit();

            for (int rowHandle = 0; rowHandle < gvLines.DataRowCount; rowHandle++)
            {
                currentPlanlamaLinesId = gvLines.GetRowCellValue(rowHandle, "PlanlamaLinesId").ToInt(-1);

                List<string> tekBilinmeyenli = new List<string>();
                List<string> cokBilinmeyenli = new List<string>();
                bool eksikPastal = false;     //dolu beden için hiç pastal girilmediyse

                if (dtDagilim != null)
                {
                    for (int dagilimIndex = 1; dagilimIndex < 29; dagilimIndex++)
                    {

                        string colName = "A" + dagilimIndex.ToString().PadLeft(2, '0');

                        foreach (DataRow drx in ds.PlanlamaDagilim.Select("PlanlamaLinesId=" + currentPlanlamaLinesId))
                            if (drx[colName].ToInt(-1) == 0)
                                drx[colName] = DBNull.Value;

                        int doluPastalAdedi = dtDagilim.Compute("Count(" + colName + ")", "").ToInt(-1);
                        int d = dtDagilim.Compute("Count(" + colName + ")", string.Empty).ToInt(-1);
                        eksikPastal |= (d > 0 && SiparisAdedi(colName) == 0) || (d == 0 && SiparisAdedi(colName) > 0);

                        if (doluPastalAdedi == 1)
                            tekBilinmeyenli.Add(colName);
                        else if (doluPastalAdedi > 1)
                            cokBilinmeyenli.Add(colName);
                    }

                    foreach (string colName in tekBilinmeyenli)
                    {
                        DataRow drDagilim = dtDagilim.Select(colName + " is not null")[0];
                        int carpan = drDagilim[colName].ToInt(-1);
                        int pkatMevcut = drDagilim["PKat"].ToInt(-1);
                        int pKat = Convert.ToInt32(Math.Ceiling(SiparisAdedi(colName) / (decimal)carpan));

                        if (pKat > pkatMevcut)
                        {
                            int planlamaDagilimId = drDagilim["PlanlamaDagilimId"].ToInt(-1);
                            ds.PlanlamaDagilim.FindByPlanlamaDagilimId(planlamaDagilimId).PKat = pKat;
                        }
                    }

                    List<string> duzeltilen = null;
                    do
                    {
                        duzeltilen = new List<string>();

                        foreach (string colName in cokBilinmeyenli)
                        {
                            DataRow[] bilinmeyen = dtDagilim.Select(colName + " is not null and PKat is null");
                            if (bilinmeyen.Length > 1)
                                continue;

                            if (bilinmeyen.Length == 0)
                            {
                                duzeltilen.Add(colName);
                                continue;
                            }


                            DataRow[] bilinen = dtDagilim.Select(colName + " is not null and PKat is not null");

                            int kapsanan = 0;
                            foreach (DataRow drDagilim in bilinen)
                            {
                                int pKat = drDagilim["PKat"].ToInt(-1);
                                int carpan = drDagilim[colName].ToInt(-1);
                                kapsanan += pKat * carpan;
                            }

                            int eklenecek = SiparisAdedi(colName) - kapsanan;

                            if (eklenecek < 0)
                                eklenecek = 0;

                            DataRow drBilinmeyen = bilinmeyen[0];
                            int planlamaDagilimId = drBilinmeyen["PlanlamaDagilimId"].ToInt(-1);
                            int carpanBilinmeyen = drBilinmeyen[colName].ToInt(-1);

                            ds.PlanlamaDagilim.FindByPlanlamaDagilimId(planlamaDagilimId).PKat = eklenecek / carpanBilinmeyen;
                            duzeltilen.Add(colName);
                        }

                        foreach (string duzgun in duzeltilen)
                            cokBilinmeyenli.Remove(duzgun);

                    }
                    while (duzeltilen.Count > 0 &&
                        cokBilinmeyenli.Count > 0);

                    eksikPastal |= cokBilinmeyenli.Count > 0;
                }

                if (eksikPastal)
                {
                    DataRow[] drt = ds.PlanlamaLinesModelhane.Select("PlanlamaLinesId=" + currentPlanlamaLinesId.ToString(), string.Empty);
                    if (drt.Length == 1)
                        ds.PlanlamaLinesModelhane.FindByPlanlamaLinesModelhaneId(drt[0]["PlanlamaLinesModelhaneId"].ToInt(-1)).SetOrtBirimMetrajNull();
                }
                else
                {
                    int toplam = 0;
                    DataRow[] drs = ds.PlanlamaDagilim.Select("PlanlamaLinesId=" + currentPlanlamaLinesId.ToString() + " AND SipKes=3 and PKat is not null");
                    for (int dagilimIndex = 1; dagilimIndex < 29; dagilimIndex++)
                    {
                        string colName = "A" + dagilimIndex.ToString().PadLeft(2, '0');
                        foreach (DataRow drDagilim in drs)
                            if (drDagilim[colName].ToInt(-1) > 0)
                                toplam += drDagilim[colName].ToInt(-1) * drDagilim["PKat"].ToInt(-1);
                    }

                    decimal uzunluk = 0;
                    foreach (DataRow dr in drs)
                        uzunluk += decimalParse(dr["PKat"]) * (decimalParse(dr["PBoy"]) + 0.04m);

                    if (toplam > 0 && uzunluk > 0)
                        MetrajEkle(currentPlanlamaLinesId, uzunluk / toplam);
                }
            }
        }




        void MetrajEkle(int PlanlamaLinesId, decimal Metraj)
        {
            DataRow[] drs = ds.PlanlamaLinesModelhane.Select("PlanlamaLinesId=" + PlanlamaLinesId.ToString(), "");
            if (drs.Length == 0)
            {
                MyData.PlanlamaLinesModelhaneRow r = ds.PlanlamaLinesModelhane.NewPlanlamaLinesModelhaneRow();
                r.PlanlamaLinesId = PlanlamaLinesId;
                r.OrtBirimMetraj = (float)Metraj;
                ds.PlanlamaLinesModelhane.AddPlanlamaLinesModelhaneRow(r);
            }
            else if (drs.Length == 1)
                ds.PlanlamaLinesModelhane.FindByPlanlamaLinesModelhaneId(drs[0]["PlanlamaLinesModelhaneId"].ToInt(-1)).OrtBirimMetraj = (float)Metraj;
        }

        void SpecifyPrdTree(object sender, EventArgs e)
        {
            //DataRow row = gv.GetDataRow(gv.FocusedRowHandle);
            //int PlanlamaId = intParse(row["PlanlamaId"]);
            using (Depo.AksesuarUrunAgaci ua = new Depo.AksesuarUrunAgaci(1))
                if (ua.ShowDialog() == DialogResult.OK)
                {
                    foreach (var handle in gv.GetSelectedRows())
                    {
                        DataRow row = gv.GetDataRow(handle);
                        row["PrdTreeId"] = ua.PrdTreeId;
                    }

                }
        }

        void CreateAksesuarTalep(object sender, EventArgs e)
        {
            string str = string.Empty;
            foreach (int rowHandle in gv.GetSelectedRows())
                str += gv.GetRowCellDisplayText(rowHandle, "PlanlamaId") + ",";

            using (Depo.AksesuarIhtiyaciPlanlama ai = new Depo.AksesuarIhtiyaciPlanlama(str))
                ai.ShowDialog();
        }
        void DosyaKapama(object sender, EventArgs e)
        {
            //int planlamaId = gv.GetRowCellValue(gv.FocusedRowHandle, "PlanlamaId").ToInt();

            string str = string.Empty;
            foreach (int rowHandle in gv.GetSelectedRows())
                str += gv.GetRowCellDisplayText(rowHandle, "PlanlamaId") + ",";

            if (str.Substring(str.Length - 1, 1) == ",")
                str = str.Substring(0, str.Length - 1);

            xrDosyaKapama xr = new xrDosyaKapama(str);
            xr.ShowPreview();

        }

        //void CreateTelaRequest(object sender, EventArgs e)
        //{
        //    if (ds.HasChanges())
        //        btnKaydet.PerformClick();

        //    string Message = string.Empty;
        //    foreach (int rowHandle in gv.GetSelectedRows())
        //        Message += gv.GetRowCellDisplayText(rowHandle, "PlanlamaId") + ",";

        //    if (Message.Substring(Message.Length - 1, 1) == ",")
        //        Message = Message.Substring(0, Message.Length - 1);

        //    DataTable dt = ds.Planlama.Select("PlanlamaId in (" + Message + ")").CopyToDataTable();
        //    int countCustomer = Convert.ToInt16(dt.Compute("Count(CustomerId)", "CustomerId=" + dt.Rows[0]["CustomerId"].ToString()));

        //    if (countCustomer < gv.GetSelectedRows().Length)
        //    {
        //        ShowMessage("Farklı müşterilere ait satırları seçemezsiniz !");
        //        return;
        //    }

        //    using (Depo.Kauf.TelaIhtiyaci ok = new Depo.Kauf.TelaIhtiyaci(Message, intParse(dt.Rows[0]["CustomerId"])))
        //        ok.ShowDialog();
        //}

        //void CreateFabricRequest(object sender, EventArgs e)
        //{
        //    if (ds.HasChanges())
        //        btnKaydet.PerformClick();

        //    string Message = string.Empty;
        //    foreach (int rowHandle in gv.GetSelectedRows())
        //        Message += gv.GetRowCellDisplayText(rowHandle, "PlanlamaId") + ",";

        //    if (Message.Substring(Message.Length - 1, 1) == ",")
        //        Message = Message.Substring(0, Message.Length - 1);

        //    DataTable dt = ds.Planlama.Select("PlanlamaId in (" + Message + ")").CopyToDataTable();
        //    int countCustomer = Convert.ToInt16(dt.Compute("Count(CustomerId)", "CustomerId=" + dt.Rows[0]["CustomerId"].ToString()));

        //    if (countCustomer < gv.GetSelectedRows().Length)
        //    {
        //        ShowMessage("Farklı müşterilere ait satırları seçemezsiniz !");
        //        return;
        //    }

        //    DataRow[] dtGarniBM = ds.PlanlamaGarniMetrajPl.Select("PlanlamaId in (" + Message + ") and (Cm>100 or Cm<1)");
        //    if (dtGarniBM.Length > 0)
        //    {
        //        XtraMessageBox.Show("Seçtiğiniz satırlarda yanlış girilmiş TAHMİNİ GARNİ BİRİM METRAJLAR var.\n\nNot: Garni birim metrajlarını CM. cinsinden giriniz !", "Critical");
        //        return;
        //    }

        //    DataRow[] dtAnaBedenBM = ds.PlanlamaLines.Select("PlanlamaId in (" + Message + ") and TahminiBM>3");
        //    if (dtAnaBedenBM.Length > 0)
        //    {
        //        XtraMessageBox.Show("Seçtiğiniz satırlarda yanlış girilmiş ANA BEDEN TAHMİNİ BİRİM METRAJLAR var.\n\nNot: Ana beden birim metrajını MT. cinsinden giriniz !", "Critical");
        //        return;
        //    }

        //    using (Depo.Kauf.OrtakKumas ok = new Depo.Kauf.OrtakKumas(Message, intParse(dt.Rows[0]["CustomerId"]), "GetOrtakKumas", true))
        //        ok.ShowDialog();

        //}

        void ExceleAktarF(object sender, EventArgs e)
        {
            string str = string.Empty;
            foreach (int rowHandle in gv.GetSelectedRows())
                str += gv.GetRowCellDisplayText(rowHandle, "PlanlamaId") + ",";

            ds.xPlanlamaXls.Clear();
            GetDetails("xPlanlamaXls", "GetPlanlamaExcel", str + "0", string.Empty, 2);
            Export();
        }

        void ExceleAktar(object sender, EventArgs e)
        {
            string str = string.Empty;
            foreach (int rowHandle in gv.GetSelectedRows())
                str += gv.GetRowCellDisplayText(rowHandle, "PlanlamaId") + ",";

            ds.xPlanlamaXls.Clear();
            GetDetails("xPlanlamaXls", "GetPlanlamaExcel", str + "0", string.Empty, 1);
            Export();
        }

        void FindSimilarArtikel(object sender, EventArgs e)
        {
            string str = string.Empty;
            foreach (int rowHandle in gvLines.GetSelectedRows())
                str += gvLines.GetRowCellDisplayText(rowHandle, "Artikel") + ",";

            ds.Merge(Session.DataManager.ExecuteDataSet("FindSimilarForPlanlama", str));

            int i = gvLines.GetSelectedRows()[0];
            foreach (int rowHandle in gvLines.GetSelectedRows())
            {
                string Artikel = (gvLines.GetRowCellValue(rowHandle, "Artikel")).ToString();
                int productId = (int)ds.Tables["Table"].Select("Kod= '" + Artikel + "'")[0]["ProductId"];
                gvLines.SetRowCellValue(rowHandle, "ProductId", productId);
            }
            ds.Tables["Table"].Clear();
        }

        void ExceleAktar2F(object sender, EventArgs e)
        {
            string str = string.Empty;
            foreach (int rowHandle in gvLines.GetSelectedRows())
                str += gvLines.GetRowCellDisplayText(rowHandle, "PlanlamaLinesId") + ",";

            ds.xPlanlamaXls.Clear();
            GetDetails("xPlanlamaXls", "GetPlanlamaExcel", string.Empty, str + "0", 2);
            Export();
        }

        void ExceleAktar2(object sender, EventArgs e)
        {
            string str = string.Empty;
            foreach (int rowHandle in gvLines.GetSelectedRows())
                str += gvLines.GetRowCellDisplayText(rowHandle, "PlanlamaLinesId") + ",";

            ds.xPlanlamaXls.Clear();
            GetDetails("xPlanlamaXls", "GetPlanlamaExcel", string.Empty, str + "0", 1);
            Export();
        }

        void DosyaAyir(object sender, EventArgs e)
        {
            string str = string.Empty;
            foreach (int rowHandle in gvLines.GetSelectedRows())
                str += gvLines.GetRowCellDisplayText(rowHandle, "PlanlamaLinesId") + ",";

            GetDetails("Planlama;PlanlamaLines", "InsGPKot", str);
        }

        private void Export()
        {
            if (ds.xPlanlamaXls.Rows.Count > 0)
            {
                GridControl gcE = new GridControl();
                GridView gvE = new GridView();
                gcE.MainView = gvE;
                gcE.DataSource = ds.xPlanlamaXls;
                gcE.BindingContext = new BindingContext();
                gcE.ForceInitialize();

                gvE.Columns["PlanlamaLinesId"].Caption = "PLinesId";
                gvE.Columns["PlanlamaDagilimId"].Caption = "PDagilimId";

                int DagilimId = intParse(ds.xPlanlamaXls.Rows[0]["DagilimId"]);
                MyData.DagilimRow dgl = AppSession.Lookups.Dagilim.FindByDagilimId(DagilimId);
                for (int i = 1; i <= 28; i++)
                {
                    string Nr = string.Format("{0:00}", i);
                    gvE.Columns["A" + Nr].Caption = dgl["A" + Nr].ToString() != string.Empty ? dgl["A" + Nr].ToString() : " ";
                    gvE.Columns["A" + Nr].Visible = gvE.Columns["A" + Nr].Caption.Trim() != string.Empty;
                }
                gvE.BestFitColumns();
                gvE.Columns["DagilimId"].Visible = false;
                gvE.RowStyle += new RowStyleEventHandler(gvE_RowStyle);

                foreach (DevExpress.XtraGrid.Columns.GridColumn col in gvE.Columns)
                    col.MinWidth = gvE.CalcColumnBestWidth(col);

                gvE.ExportToExcel();
            }
        }

        void gvE_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView gvE = (GridView)sender;
            e.Appearance.BorderColor = Color.White; // gvE.GetRowCellDisplayText(e.RowHandle, "DosyaNo") != string.Empty ? Color.Gray : Color.White;
            e.Appearance.ForeColor = gvE.GetRowCellDisplayText(e.RowHandle, "Tip") == "Fark" ? Color.Crimson : Color.Black;
            e.Appearance.BackColor = gvE.GetRowCellDisplayText(e.RowHandle, "Tip") == "" ? Color.LightGray : Color.White;   //Beige?
        }        

        private void Exp0()
        {
            gvDagilim.CloseEditor();
            EndEdits();

            ds.PlanlamaDagilim.Columns["Total"].Expression =
            ds.PlanlamaDagilim.Columns["S"].Expression =
            ds.PlanlamaDagilim.Columns["K"].Expression =
            ds.PlanlamaDagilim.Columns["PMetraj"].Expression =

            ds.PlanlamaLines.Columns["Yuklenen"].Expression =
            ds.PlanlamaLines.Columns["Yuklenen2Kalite"].Expression =
            ds.PlanlamaLines.Columns["YuklemeTarihi"].Expression =
            ds.PlanlamaLines.Columns["SiparisAdedi"].Expression =
            ds.PlanlamaLines.Columns["Kesilen"].Expression =
            ds.PlanlamaLines.Columns["SarfedilenMt"].Expression =
            ds.PlanlamaLines.Columns["Kalite2"].Expression =
            ds.PlanlamaLines.Columns["Kalite3"].Expression =
            ds.PlanlamaLines.Columns["PastalBM"].Expression =

            ds.Planlama.Columns["SiparisAdedi"].Expression =
            ds.Planlama.Columns["KesimAdedi"].Expression =
            ds.Planlama.Columns["Yuklenen"].Expression =
            ds.Planlama.Columns["KalanKalite1"].Expression =
            ds.Planlama.Columns["Iptal"].Expression =
            ds.Planlama.Columns["Kalite2"].Expression =
            ds.Planlama.Columns["Kalite3"].Expression =
            ds.Planlama.Columns["FaturaAdedi"].Expression =
            ds.Planlama.Columns["Adet"].Expression =

            ds.Planlama.Columns["YuklemeTarihi"].Expression =
            ds.Planlama.Columns["YuklemeHaftasi"].Expression =
            ds.Planlama.Columns["YuklemeAyi"].Expression =
            ds.Planlama.Columns["Fark"].Expression =
            ds.Planlama.Columns["FaturaFark"].Expression =
            ds.Planlama.Columns["FaturaDurumu"].Expression =
            string.Empty;

        }

        private void Exp1()
        {
            ds.PlanlamaDagilim.Columns["Total"].Expression = "IsNull(A01, 0) + IsNull(A02, 0) + IsNull(A03, 0) + IsNull(A04, 0) + IsNull(A05, 0) + IsNull(A06, 0) + IsNull(A07, 0) + IsNull(A08, 0) + IsNull(A09, 0) + IsNull(A10, 0) + IsNull(A11, 0) + IsNull(A12, 0) + IsNull(A13, 0) + IsNull(A14, 0) + IsNull(A15, 0) + IsNull(A16, 0) + IsNull(A17, 0) + IsNull(A18, 0) + IsNull(A19, 0) + IsNull(A20, 0) + IsNull(A21, 0) + IsNull(A22, 0) + IsNull(A23, 0) + IsNull(A24, 0) + IsNull(A25, 0) + IsNull(A26, 0) + IsNull(A27, 0) + IsNull(A28, 0)";
            ds.PlanlamaDagilim.Columns["S"].Expression = "Iif(SipKes = 1, Total, 0)";
            ds.PlanlamaDagilim.Columns["K"].Expression = "Iif(SipKes = 2, Total, 0)";
            ds.PlanlamaDagilim.Columns["PMetraj"].Expression = "Iif(ISNULL(Total,0)>0, PBoy/Total, Null)";

            ds.PlanlamaLines.Columns["Yuklenen"].Expression = "Sum(Child(FK_PlanlamaLinesInvoice_PlanlamaLines_PlanlamaLinesId).YuklenenAdet)";
            ds.PlanlamaLines.Columns["Yuklenen2Kalite"].Expression = "Sum(Child(FK_PlanlamaLinesInvoice_PlanlamaLines_PlanlamaLinesId).Yuklenen2Kalite)";
            ds.PlanlamaLines.Columns["YuklemeTarihi"].Expression = "MAX(Child(FK_PlanlamaLinesInvoice_PlanlamaLines_PlanlamaLinesId).YuklemeTarihi)";
            ds.PlanlamaLines.Columns["SiparisAdedi"].Expression = "Sum(Child(FK_PlanlamaDagilim_PlanlamaLines_PlanlamaLinesId).S)";
            ds.PlanlamaLines.Columns["Kesilen"].Expression = "Sum(Child(FK_PlanlamaDagilim_PlanlamaLines_PlanlamaLinesId).K)";
            ds.PlanlamaLines.Columns["Kalite2"].Expression = "Sum(Child(FK_PlanlamaLinesHatalar_PlanlamaLines_PlanlamaLinesId).Kalite2)";
            ds.PlanlamaLines.Columns["Kalite3"].Expression = "Sum(Child(FK_PlanlamaLinesHatalar_PlanlamaLines_PlanlamaLinesId).Kalite3)";
            ds.PlanlamaLines.Columns["PastalBM"].Expression = "MAX(Child(FK_PlanlamaLinesModelhane_PlanlamaLines_PlanlamaLinesId).OrtBirimMetraj)";
            ds.PlanlamaLines.Columns["SarfedilenMt"].Expression = "Kesilen*PastalBM";

            //ds.PlanlamaLinesBM.Columns["ToplamBM"].Expression = "ISNULL(Garni1Cm,0)+ISNULL(Garni2Cm,0)+ISNULL(Garni3Cm,0)+ISNULL(Garni4Cm,0)+ISNULL(Garni5Cm,0)+ISNULL(BedenBM,0)";

            ds.Planlama.Columns["SiparisAdedi"].Expression = "Sum(Child(FK_PlanlamaLines_Planlama_PlanlamaId).SiparisAdedi)";
            ds.Planlama.Columns["KesimAdedi"].Expression = "Sum(Child(FK_PlanlamaLines_Planlama_PlanlamaId).Kesilen)";
            ds.Planlama.Columns["Yuklenen"].Expression = "Sum(Child(FK_PlanlamaLines_Planlama_PlanlamaId).Yuklenen)";
            ds.Planlama.Columns["KalanKalite1"].Expression = "Sum(Child(FK_PlanlamaLines_Planlama_PlanlamaId).KalanKalite1)";
            ds.Planlama.Columns["Iptal"].Expression = "Sum(Child(FK_PlanlamaLines_Planlama_PlanlamaId).Iptal)";
            ds.Planlama.Columns["Kalite2"].Expression = "Sum(Child(FK_PlanlamaLines_Planlama_PlanlamaId).Kalite2)";
            ds.Planlama.Columns["Kalite3"].Expression = "Sum(Child(FK_PlanlamaLines_Planlama_PlanlamaId).Kalite3)";
            ds.Planlama.Columns["FaturaAdedi"].Expression = "Sum(Child(FK_PlanlamaFatura_Planlama_PlanlamaId).Adet)";
            ds.Planlama.Columns["FaturaFark"].Expression = "Iif(IsNull(FaturaAdedi,0)=IsNull(KesimAdedi,0), null, IsNull(FaturaAdedi,0)-IsNull(KesimAdedi,0))";
            ds.Planlama.Columns["Adet"].Expression = "Iif(COUNT(Child(FK_PlanlamaFatura_Planlama_PlanlamaId).PlanlamaFaturaId)>0, COUNT(Child(FK_PlanlamaFatura_Planlama_PlanlamaId).PlanlamaFaturaId), null)";

            ds.Planlama.Columns["YuklemeTarihi"].Expression = "MAX(Child(FK_PlanlamaLines_Planlama_PlanlamaId).YuklemeTarihi)";
            ds.Planlama.Columns["YuklemeHaftasi"].Expression = "YuklemeTarihi";
            ds.Planlama.Columns["YuklemeAyi"].Expression = "YuklemeTarihi";
            ds.Planlama.Columns["Fark"].Expression = "IsNull(Yuklenen,0)+IsNull(KalanKalite1,0)+IsNull(EksikAdet,0)+IsNull(Numune,0)+IsNull(Iptal,0)+IsNull(Kalite2,0)+IsNull(Kalite3,0)-IsNull(KesimAdedi,0)";
            ds.Planlama.Columns["FaturaDurumu"].Expression = "Iif(IsNull(KesimAdedi,0) = 0, null, Iif(IsNull(KesimAdedi,0) = IsNull(FaturaAdedi,0), 'FATURA OK', Iif(IsNull(KesimAdedi,0) > IsNull(FaturaAdedi,0), 'EKSİK FATURA', 'FAZLA FATURA')))";
        }

        void gvListe_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (!gv.OptionsView.AllowCellMerge)
                if (e.RowHandle % 2 == 0 && e.Appearance.BackColor == Color.White)
                    e.Appearance.BackColor = colors[((BandedGridColumn)e.Column).OwnerBand.Index];

            if (e.RowHandle >= 0)
                switch (e.Column.FieldName)
                {
                    //case "Fark":
                    //case "Fark2":
                    case "CustomerId":
                    case "DosyaNo":
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        break;
                }

        }

        void gv_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            /*
            Dosya girişi  –Mevlüde
            Modelhane     -Serpil   * gerek var mı?
            Kumaş metraj  -ilker
            Dosya kapama  -ilker  
            */
            //string[] parts = "DOSYA BİLGİLERİ;KESİLEN ADET DAĞILIMI;YÜKLEME TARİHİ;FATURA;ÜRETİMDEN KALAN KUMAŞ TAKİBİ".Split(';');
            // switch (((BandedGridColumn)gvListe.FocusedColumn).OwnerBand.Index)

            //if (gv.FocusedColumn.FieldName == "DosyaNo" && gv.GetFocusedRowCellDisplayText("DosyaNo").Length > 7)

            if (gv.FocusedRowHandle > -1)
                if (!ytk(173) && gv.FocusedColumn.FieldName == "DagilimId" && gv.GetFocusedRowCellDisplayText("SiparisAdedi").ToInt() > 0 && gv.GetFocusedRowCellDisplayText("PlanlamaId").ToInt() > 0)
                    e.Cancel = true;
                else
                    switch (gv.FocusedColumn.FieldName)
                    {
                        case "DosyaTeslimTarihi":
                            e.Cancel = !(ytk(89) || ytk(91) && gv.GetFocusedDataRow()["CustomerId"].ToInt() == 22); //89(tülay,fevzi,özcan),91(fatmaseda,gökçe)
                            break;

                        default:
                            e.Cancel = false;
                            break;
                    }

        }

        void Planlama_EditValueChanged(object sender, EventArgs e)
        {
            DagilimChanged((sender as BaseEdit).EditValue);
        }

        private void DagilimChanged(object val)
        {
            try
            {
                DagilimId = intParse(val);
                MyData.DagilimRow r = AppSession.Lookups.Dagilim.FindByDagilimId(DagilimId);
                if (r != null)
                    if (gvDagilim.Columns.Count > 0)
                    {
                        for (int i = 1; i <= 28; i++)
                        {
                            string beden = String.Format("A{0:00}", i);
                            string cap = r[beden].ToString();
                            gvDagilim.Columns[beden].Caption = cap;   //AppSession.Lookups.Dagilim.FindByDagilimId(DagilimId)[beden].ToString();
                            gvDagilim.Columns[beden].VisibleIndex = AppSession.Lookups.Dagilim.FindByDagilimId(DagilimId)[beden].ToString() != string.Empty ? 100 + i : -1;
                        }
                        gvDagilim.BestFitColumns();
                    }

            }
            catch (Exception Ex)
            {
                Notify("DagilimChanged: " + val.ToString());
                throw Ex;
            }
        }

        void Planlama_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["DagilimId"] = DagilimId;
            //e.Row["DosyaTeslimTarihi"] = DateTime.Now;
        }

        void PlanlamaLines_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            for (int i = 1; i <= 2; i++)
            {
                MyData.PlanlamaDagilimRow r0 = ds.PlanlamaDagilim.NewPlanlamaDagilimRow();
                r0.SipKes = i;
                r0.PlanlamaLinesId = (int)e.Row["PlanlamaLinesId"];
                ds.PlanlamaDagilim.AddPlanlamaDagilimRow(r0);
            }
        }

        bool DosyaNolari()
        {
            bs.EndEdit();

            if (ds.Planlama.Select("CustomerId is null AND BrandId is null AND PlanlamaId < 0").Length > 0)
            {
                XtraMessageBox.Show("Hem marka hem müşterisi boş olan satırlar var. Bunları düzeltmeden kaydedemezsiniz !", "Hata");
                return false;
            }

            string str = string.Empty;
            foreach (DataRow dr in ds.Planlama.Select("ISNULL(DosyaNo,'')=''"))
                str += dr["PlanlamaId"].ToString() + Environment.NewLine;
            if (str != string.Empty)
            {
                XtraMessageBox.Show(str, "Şu satırların DOSYANO.ları geçerli değil !");
                return false;
            }


            DataTable dt = new DataTable("Table1");
            dt.Columns.Add("PlanlamaId", typeof(int));
            dt.Columns.Add("DosyaNo", typeof(string));
            foreach (DataRow dr in ds.Planlama.Select("DosyaNo in ('K', 'F', 'N', 'D')"))
                dt.Rows.Add(intParse(dr["PlanlamaId"]), dr["DosyaNo"].ToString());

            if (dt.Rows.Count > 0)
            {
                ds.xDosyaNo.Clear();
                GetDetails("xDosyaNo", "UpdDosyaNo", dt.SerializeChanges());

                foreach (MyData.xDosyaNoRow r in ds.xDosyaNo.Rows)
                {
                    int p = intParse(r["PlanlamaId"]);
                    if (ds.Planlama.FindByPlanlamaId(p) != null)
                        ds.Planlama.FindByPlanlamaId(p).DosyaNo = r["DosyaNo"].ToString();
                }
            }
            return true;
        }

        private void PrepareImageComboBoxEdit(GridView gv, string colName)
        {
            RepositoryItemImageComboBox imageCombo = gv.GridControl.RepositoryItems.Add("ImageComboBoxEdit") as RepositoryItemImageComboBox;
            imageCombo.Items.BeginUpdate();
            int ndx = 0;
            imageCombo.SmallImages = noktalar;
            foreach (string opt in "FATURA OK|EKSİK FATURA|FAZLA FATURA".Split('|'))
                imageCombo.Items.Add(new ImageComboBoxItem(opt, ndx++));
            //imageCombo.GlyphAlignment = DevExpress.Utils.HorzAlignment.Default;
            imageCombo.Items.EndUpdate();
            gv.Columns[colName].ColumnEdit = imageCombo;
        }





        public BaseRow AddItem(string name, Type t, params RepositoryItem[] ri)
        {
            return AddItem(vgc, name, t, ri);
        }

        object GetVal(string FieldName)
        {
            return vgc.GetCellValue(vgc.Rows[FieldName], vgc.FocusedRecord);
        }

        private void CreateVerticalGrid()
        {
            vgc.Rows.AddRange(new BaseRow[] {
                AddItem("Durum", typeof(string), riGenel),
                AddItem("TipeGöreAyır", typeof(bool)),

                AddItem("stYuklemeId", typeof(int), GetCustomRI("Yükleme",true, "Aktif", "Yüklenen", "Tümü")),
                AddItem("PlanlamaId", typeof(int)),
                AddItem("PlanlamaLinesId", typeof(int)),
                AddItem("KaufIdx", typeof(int)),
                AddItem("CKBatchId", typeof(int), RI(Rp.CKBatch)),
                AddItem("NumuneUretim", typeof(int), GetCustomRI("Numune Üretim",false, "NUMUNE", "ÜRETİM", "KOLEKSİYON") ),
                AddItem("AtelyeId", typeof(int), RI(Rp.Atelye)),
                AddItem("DosyaTeslimTarihi", typeof(DateTime), new RepositoryItemDateEdit()),
                AddItem("TerminTarihi", typeof(DateTime), new RepositoryItemDateEdit()),
                AddItem("YuklemeHaftasi", typeof(DateTime), new RepositoryItemDateEdit()),
                AddItem("BrandId", typeof(int), RI(Rp.Brand)),
                AddItem("CustomerId", typeof(int), RI(Rp.V_Customer)),
                AddItem("Line", typeof(string)),
                AddItem("Model", typeof(string)),
                AddItem("Artikel", typeof(string)),
                AddItem("Kalip", typeof(string)),
                AddItem("Etiket", typeof(string)),
                AddItem("InvoiceNo", typeof(string)),
                AddItem("DosyaNo", typeof(string)),
                AddItem("NOTLAR1", typeof(string), new RepositoryItemMemoEdit())
            });

            vgc.Rows.GetRowByFieldName("NOTLAR1", true).Height = 60;
            //((RepositoryItemGridLookUpEdit)vgc.Rows.GetRowByFieldName("stGenelId", true).Properties.RowEdit).TextEditStyle = TextEditStyles.DisableTextEditor;    //OA*
            vgc.SetCellValue(vgc.Rows["Durum"], 0, "AÇIK");
            vgc.FocusedRow = vgc.Rows["Durum"];

            vgc.OptionsBehavior.UseEnterAsTab = true;
            vgc.LayoutStyle = DevExpress.XtraVerticalGrid.LayoutViewStyle.SingleRecordView;
            vgc.CustomDrawRowHeaderCell += new CustomDrawRowHeaderCellEventHandler(vgc_CustomDrawRowHeaderCell);
            vgc.Appearance.RowHeaderPanel.BackColor = Color.LightBlue;
            //            vgc.RecordWidth = splitContainerControl2.Panel1.Width - vgc.RowHeaderWidth - 3;

            //vgc.SetCellValue(vgc.Rows["stGenelId"], 0, 1);
            //vgc.SetCellValue(vgc.Rows["stYuklemeId"], 0, 3);

            if (ytk(86))//*
                vgc.SetCellValue(vgc.Rows["TipeGöreAyır"], 0, false);
            else
                vgc.SetCellValue(vgc.Rows["TipeGöreAyır"], 0, true);
            vgc.FocusedRow = vgc.Rows["DosyaNo"];
            vgc.BestFit();
        }

        void btnGetir_Click(object sender, EventArgs e)
        {
            if (btnKaydet.Enabled)
                if (ds.HasChanges())
                    if (XtraMessageBox.Show("Değişiklikleri kaydetmek ister misiniz?", "Critical", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                        btnKaydet.PerformClick();

            ClearTables();

            //gv.BeginDataUpdate();
            //gvLines.BeginDataUpdate();
            //gvDagilim.BeginDataUpdate();
            //gvGarni.BeginDataUpdate();
            //gvGarniArt.BeginDataUpdate();
            //gvGarniPl.BeginDataUpdate();
            //gvHatalar.BeginDataUpdate();
            //gvModelhane.BeginDataUpdate();
            //gvMyTreeLines.BeginDataUpdate();
            //gvTela.BeginDataUpdate();

            GetDetails("Planlama;PlanlamaLines;PlanlamaLinesHatalar;PlanlamaLinesGarni;PlanlamaLinesModelhane;PlanlamaDagilim;PlanlamaFatura;PlanlamaLinesInvoice;PlanlamaLinesAksesuar;PlanlamaLinesTela;PlanlamaGarniMetraj;PlanlamaGarniMetrajPl", "GetPlanlamaFiltered2",
                strParse(GetVal("Durum")),
                //intParse(GetVal("stGenelId")),
                boolParse(GetVal("TipeGöreAyır")),
                intParse(GetVal("stYuklemeId")),
                datetimeParse(GetVal("DosyaTeslimTarihi")),
                datetimeParse(GetVal("TerminTarihi")),
                datetimeParse(GetVal("YuklemeHaftasi")),
                strParse(GetVal("NumuneUretim")),
                strParse(GetVal("Line")),
                strParse(GetVal("Model")),
                strParse(GetVal("Kalip")),
                strParse(GetVal("InvoiceNo")),
                strParse(GetVal("DosyaNo")),
                strParse(GetVal("NOTLAR")),
                intParse(GetVal("PlanlamaId")),
                intParse(GetVal("PlanlamaLinesId")),
                intParse(GetVal("KaufIdx")),
                intParse(GetVal("CKBatchId")),
                intParse(GetVal("CustomerId")),
                intParse(GetVal("BrandId")),
                intParse(GetVal("AtelyeId")),
                strParse(GetVal("Artikel")),
                strParse(GetVal("Etiket")),
                WhoAmI);

            //gvCELines.FocusedRowHandle = gvCELines.LocateByDisplayText(0, gvCELines.Columns["Hit"], "1");
            //gvCELines2.FocusedRowHandle = gvCELines2.LocateByDisplayText(0, gvCELines2.Columns["Hit"], "1");

            vgc.Rows.GetRowByFieldName("TipeGöreAyır", true).Properties.ToolTip = "Seçili ise, planlamacılara ÜRETİM, müşteri temsilcilerine KOLEKSİYON ve NÜMUNE siparişlerini göstererek diğerlerini gizler.";

            //gv.EndDataUpdate();
            //gvLines.EndDataUpdate();
            //gvDagilim.EndDataUpdate();
            //gvGarni.EndDataUpdate();
            //gvGarniArt.EndDataUpdate();
            //gvGarniPl.EndDataUpdate();
            //gvHatalar.EndDataUpdate();
            //gvModelhane.EndDataUpdate();
            //gvMyTreeLines.EndDataUpdate();
            //gvTela.EndDataUpdate();         

            gv.BestFitColumns();
            gvLines.BestFitColumns();
            gvGarniArt.BestFitColumns();
            gvGarniPl.BestFitColumns();
            gvGarni.BestFitColumns();

            gv.Columns["PrdTreeId"].Width = 100;

            txtInfo.Caption = strParse(bs, "DosyaNo");
            DagilimChanged(intParse(bs, "DagilimId"));

            Notify("Done.");
        }

        void btnTemizle_Click(object sender, EventArgs e)
        {
            foreach (BaseRow r in vgc.Rows)
                vgc.SetCellValue(r, 0, null);

            vgc.SetCellValue(vgc.Rows["stGenelId"], 0, 1);
        }

        private void ClearTables()
        {
            ds.Planlama.Clear();
            ds.PlanlamaLines.Clear();
            ds.PlanlamaGarniMetraj.Clear();
            ds.PlanlamaGarniMetrajPl.Clear();
            ds.PlanlamaLinesModelhane.Clear();
            ds.PlanlamaLinesHatalar.Clear();
            ds.PlanlamaDagilim.Clear();
            ds.PlanlamaFatura.Clear();
            ds.PlanlamaLinesInvoice.Clear();
            ds.AcceptChanges();
        }

        private void dockPanel1_Click(object sender, EventArgs e)
        {

        }

    }
}
